import React, { useState } from "react";
import { Form, Input, Button, Upload, message, UploadFile } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import api from "../../utils/request";

// 定义表单数据类型
interface FormValues {
  name: string;
  email: string;
  file: any; // 存储文件信息
}

const FormPage: React.FC<{ initialValues?: FormValues }> = ({
  initialValues,
}) => {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 表单提交处理函数
  const onFinish = async (values: FormValues) => {
    console.log("Form values:", values);
    console.log("File list:", fileList);
    const formData = new FormData();
    formData.append("name", values.name);
    formData.append("email", values.email);
    fileList.forEach((file) => {
      formData.append("files", file.originFileObj || "");
    });

    try {
      // 模拟 POST 请求，假设接口路径为 /submit-form
      const response = await api.post("/submit-form", formData);
      console.log("请求成功", response);
      message.success("表单提交成功");
    } catch (error) {
      console.error("请求失败", error);
      message.error("表单提交失败，请重试");
    }
  };

  // 重置表单
  const onReset = () => {
    form.resetFields();
    setFileList([]);
  };

  // 处理文件上传
  const handleChange = ({ fileList }: { fileList: UploadFile[] }) => {
    setFileList(fileList);
  };

  // 若有初始值，设置表单数据
  if (initialValues) {
    form.setFieldsValue(initialValues);
  }

  return (
    <div className="p-4">
      <Form
        form={form}
        name="formPage"
        onFinish={onFinish}
        initialValues={initialValues}
        className="max-w-md mx-auto"
      >
        <Form.Item
          name="name"
          label="姓名"
          rules={[{ required: true, message: "请输入姓名!" }]}
        >
          <Input className="w-full" />
        </Form.Item>
        <Form.Item
          name="email"
          label="邮箱"
          rules={[{ required: true, message: "请输入邮箱!", type: "email" }]}
        >
          <Input className="w-full" />
        </Form.Item>
        <Form.Item label="文件上传">
          <Upload
            fileList={fileList}
            onChange={handleChange}
            beforeUpload={() => false} // 阻止自动上传
          >
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        </Form.Item>
        <Form.Item className="flex gap-2">
          <Button type="primary" htmlType="submit" className="w-1/2">
            提交
          </Button>
          <Button htmlType="button" onClick={onReset} className="w-1/2">
            重置
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default FormPage;
